<template>
  <div class="app-container">
    <el-card>
      <div class="main-title">基地管理</div>
      <!-- 查询 -->
      <div class="search-card">
        <div class="search-form">
          <el-form :model="searchForm" >
            <div class="search-form-item">
              <el-button type="primary" icon="el-icon-plus" size="medium" @click="btnEdit('add', -1)">新增</el-button>
            </div>
            <el-divider class="mr-20" direction="vertical" />
            <div class="search-form-item">
              <i class="el-icon-search" />
              <span>查询：</span>
            </div>
            <div class="search-form-item">
              <el-input v-model.trim="searchForm.baseName" size="medium" placeholder="基地名称" />
            </div>
            <div class="search-form-item">
              <el-button size="medium" type="primary" @click='search()'>查询</el-button>
              <el-button size="medium" @click="resetForm">清空</el-button>
            </div>
          </el-form>
        </div>
      </div>
      <!-- 列表区域 -->
      <el-table
        v-loading="listLoading"
        class="table-area"
        :data="tableData"
        :header-cell-style="headerCellStyle"
      >
        <el-table-column prop="baseCode" label="基地编号" />
        <el-table-column prop="baseName" label="基地名称" />
        <el-table-column prop="companyName" label="企业名称" />
        <el-table-column prop="soilTypeName" label="土壤类型" />
        <el-table-column prop="area" label="面积(亩)" />
        <el-table-column prop="chargeName" label="负责人" />
        <el-table-column prop="chargeTel" label="联系方式" />
        <el-table-column label="操作" width="280px">
          <template slot-scope="scope">
            <el-button
              class="self-btn normal-btn"
              type="text"
              icon="el-icon-edit"
              @click="btnEdit('update', scope.row)"
            >修改</el-button>
            <el-button
              class="self-btn delete-btn"
              type="text"
              icon="el-icon-close"
              :disabled="scope.row.status === 1 ? true : false"
              @click="deleteRow(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-main">
        <el-pagination
          background
          :page-size="searchForm.pageSize"
          :current-page="searchForm.pageNo"
          :hide-on-single-page="isPagination"
          layout="total, prev, pager, next"
          @current-change="handleCurrentChange"
          :total="total"
        />
      </div>
    </el-card>
    <el-dialog :title="editTitle+'基地信息'" :visible.sync="dialogFormVisible" :width="dialogWidth" :close-on-click-modal="false" @close="closeDialog()">
      <el-form ref="form" size="medium" :rules="fromRules" :model="form" class="dialog-form" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="12">
            <el-form-item label="基地编号" prop="baseCode">
              <el-input v-model.trim="form.baseCode" disabled placeholder="请填写基地编号" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基地名称" prop="baseName">
              <el-input v-model.trim="form.baseName" placeholder="请填写基地名称" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属企业" prop="companyId">
              <el-select
                v-model="form.companyId"
                placeholder="请选择所属企业"
              >
                <el-option
                  v-for="item in sysList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="土壤类型" prop="soilType">
              <el-select v-model="form.soilType" size="medium" placeholder="请选择土壤类型" >
                <el-option v-for="item in soilTypeList" :key="item.name" :label="item.name" :value="item.id"/>
              </el-select>
              <!--<el-input v-model.trim="form.soilType" placeholder="请填写土壤类型" />-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="面积(亩)" prop="area">
          <el-input type="number" v-model.trim="form.area" placeholder="请填写面积" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="坐标" prop="longitude">
              <el-input type="number" v-model.trim="form.longitude" class="mb-10" placeholder="经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" prop="latitude">
              <el-input type="number" v-model.trim="form.latitude" placeholder="纬度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="chargeName">
              <el-input v-model.trim="form.chargeName" placeholder="请填写负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="chargeTel">
              <el-input v-model.trim="form.chargeTel" placeholder="请填写联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="基地概况" prop="remarks">
          <el-input v-model.trim="form.remarks" type="textarea" placeholder="请填写地面概况" />
        </el-form-item>
        <el-form-item label="基地照片" prop="picturesList">
          <el-upload
            action="no"
            :limit=9
            :file-list="fileList"
            list-type="picture-card"
            :before-upload="beforeAvatarUpload"
            :on-exceed="handleExceed"
            :on-remove="handRemove"
            :http-request="upload">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="white-btn" size="small" @click="cancle()">取 消</el-button>
        <el-button type="primary" class="green-btn" size="small"  @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getTableList, addItem, updateItem, deleteItem, getSysOfficeTree, delBaseManagePicture, getBaseManageListsByCondition } from '@/api/basic/land'
import { getToken } from '@/utils/auth'
import {getDictionaryTypeList} from '@/api/sysSettings/dictManage'
import axios from 'axios'
export default {
  name: 'Product',
  data() {
    // 校验手机号码
    let isPoneAvailable = (phone) => {
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (reg.test(phone)) {
        return true
      } else {
        return false
      }
    }
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      sysList: [],
      dialogWidth: '646px', // 双列弹窗
      tableData: [],
      listLoading: false,
      headerCellStyle() {
        return 'background-color: #f5f7fa;color: #606266'
      }, // 表格表头样式
      searchForm: {
        pageSize: 10,
        pageNo: 1
      },
      editTitle: '新增',
      type: 'add',
      dialogFormVisible: false,
      total: null,
      form: {},
      formLabelWidth: '80px',
      isPagination:true,
      id: '',
      ids: [],
      fileList: [],
      soilTypeList: [], //土壤类型
      fromRules: {
        baseName: [
          { required: true, message: '请填写基地名称', trigger: 'blur' }
        ],
        area: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('请填写面积'))
              } else if (+value <= 0) {
                return callback(new Error('面积不可为空为负'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        latitude: [
          { required: true, message: '请填写纬度', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '请填写经度', trigger: 'blur' }
        ],
        chargeName: [
          { required: true, message: '请填写负责人', trigger: 'blur' }
        ],
        chargeTel: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === '') {
                return callback(new Error('请填写联系方式'))
              } else if (!isPoneAvailable(value)) {
                return callback(new Error('手机号不合法,请重新填写'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.initTable()
    this.getSysOfficeTree()
    getDictionaryTypeList({pageNo: 1,pageSize: 100,code: "soil_type"}).then(res => {
      this.soilTypeList = res.object.list[0].sysDictList
    })
  },
  methods: {
    // 获取组织机构
    getSysOfficeTree(){
      getSysOfficeTree().then(res => {
        if(+res.stateCode === 200) {
          this.sysList = res.object
        }
      })
    },
    // 列表初始化
    initTable() {
      this.listLoading = true
      getTableList(this.searchForm).then(res => {
        if(+res.stateCode === 200) {
          this.tableData = res.object.list
          this.total = res.object.total
          if(res.object.hasNextPage) {
            this.isPagination = false
          } else {
            this.isPagination = true
          }
        }
      }).catch(() => {

      }).finally(() => {
        this.listLoading = false
      })
    },
    // 查询
    search() {
      this.listLoading = true
      this.initTable()
     /* getBaseManageListsByCondition(this.searchForm).then(res => {
        if(res.stateCode === '200') {
          this.tableData = res.object.list
          if(res.object.hasNextPage) {
            this.total = res.object.total
            this.isPagination = false
          } else {
            this.total = res.object.total
            this.isPagination = true
          }
        }
      }).finally(() => {
        this.listLoading = false
      })*/
    },
    // 新增
    btnEdit(type, data) {
      this.form = {
        baseCode: data.baseCode,
        baseName: data.baseName,
        companyId: data.companyId,
        soilType: data.soilType,
        area: data.area,
        longitude: data.longitude,
        latitude: data.latitude,
        remarks: data.remarks,
        chargeName: data.chargeName,
        chargeTel: data.chargeTel
      }

      this.type = type
      this.dialogFormVisible = true
      if (type === 'update') {
        this.ids = []
        this.fileList = []
        this.editTitle = '修改'
        if(data.picturesList.length > 0) {
          data.picturesList.map(item => {
            let params = {
              url: process.env.VUE_APP_BASE_API+'/image/'+ item.imgUrl,
              id: item.id
            }
            this.fileList.push(params)
            this.ids.push(item.id)
          })
        }
        this.id = data.id
      } else if (type === 'add') {
        this.editTitle = '新增'
      }
    },
    // 新增保存
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.type === 'update') {
            this.form['id'] = this.id
            this.form['ids'] = this.ids.join(',')
            updateItem(this.form).then(res => {
              if(+res.stateCode === 200) {
                this.$message({
                  type: 'success',
                  message:res.message ,
                })
                this.dialogFormVisible = false
                this.initTable()
              }
            }).catch(() => {

            })
          } else if (this.type === 'add') {
            this.form['ids'] = this.ids.join(',')
            addItem(this.form).then(res => {
              if(+res.stateCode === 200) {
                this.$message({
                  type: 'success',
                  message:res.message ,
                })
                this.dialogFormVisible = false
                this.initTable()
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    // 搜索重置
    resetForm() {
      this.searchForm = { pageNo: 1, pageSize: 10 }
      this.initTable()
    },
    // 删除
    deleteRow(val) {
      this.$confirm('确定要删除吗?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = { id: val }
        deleteItem(param).then(response => {
          this.$message.success('删除成功')
          let totalPage = Math.ceil((Number(this.total) - 1) / this.searchForm.pageSize)
          this.searchForm.pageNo = this.searchForm.pageNo > totalPage && totalPage > 0 ? totalPage : this.searchForm.pageNo
          this.initTable()
        })
      })
      .catch((action) => {})
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return  isLt2M;

    },
    handleExceed(files, fileList) {
      this.$message.error("上传图片不能超过1张!");
    },
    upload(val) {
      let fd = new FormData();
      fd.append('baseManageId','');
      fd.append('file',val.file);
      axios.post(process.env.VUE_APP_BASE_API+'/base/addBaseManagePicture',fd,{headers:{ 'content-type': 'application/x-www-form-urlencoded','Authorization': 'Bearer ' + getToken() }}).then(res => {
        if(res.data.stateCode === '200') {
          this.ids.push(res.data.object.id)
          let params = {
            url: process.env.VUE_APP_BASE_API+'/image/'+ res.data.object.imgURL,
            id: res.data.object.id
          }
          this.fileList.push(params)
          this.$message({
            type: 'success',
            message:res.data.message ,
          })
        }
      })
    },
    // 删除图片
    handRemove(file,fileList) {
      this.ids = []
      const params = {
        imgId: file.id
      }
      delBaseManagePicture(params).then(res => {
        if(res.stateCode === '200') {
          this.fileList = fileList
          fileList.map(item => {
            this.ids.push(item.id)
          })
          this.$message({
            type: 'success',
            message:res.message ,
          })
        }
      })
    },
    //this.fileList = []
    //this.ids = []
    cancle() {
      this.dialogFormVisible = false
      this.fileList = []
      this.ids = []
    },
    closeDialog() {
      this.fileList = []
      this.ids = []
    },
    // 改变当前页
    handleCurrentChange(val) {
      this.searchForm.pageNo = val
      this.initTable()
    },
  }
}
</script>
<style lang="scss">
  .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 78px;
      height: 78px;
      line-height: 78px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
</style>
<style lang="scss" scoped>
.btn-group {
  padding: 16px 20px;
}
.table-area {
  padding: 0 20px;
}
.product-status {
  width: 58px;
  height: 28px;
  line-height: 28px;
  display: inline-block;
  text-align: center;
  border-radius: 4px;
  background: #f2fff7;
  border: 1px solid #1eb955;
  color: #1eb955;
}
.product-status.active {
  background: #f3f3f3;
  border: 1px solid #999;
  color: #999;
}

// 查询区域
.search-card {
  padding: 16px 22px;
  display: flex;
  align-items: center;
  background-color: #FFF;
  .query-text {
    width: 80px;
  }
  .search-form {
    .search-form-item {
      display: inline-block;
      margin-right: 10px;
      margin-bottom: 6px;
    }
  }
}
</style>
